/**
 * Created by wangshuo on 2017/2/16.
 */

angular.module('BlurAdmin.profile', [])
    .service('ProfileService', function () {

        this.VERSION = "V0.9.13";
        this.DEBUG_MODE = true;

        this.SERVER_HOST = this.DEBUG_MODE ? 'http://127.0.0.1:8081/molin/' : '/molin/';
        this.TOKEN_SERVICE = this.SERVER_HOST + 'auth/token/';

        this.SERVICE_NAVIGATION_PIC = this.SERVER_HOST + "resources/navpics/";
        this.SERVICE_NAVIGATION_PIC_QUERY = this.SERVICE_NAVIGATION_PIC + "collections/";
        this.SERVICE_NAVIGATION_PIC_LINKS = this.SERVICE_NAVIGATION_PIC + "links/";

        this.SERVICE_NAVIGATION_PIC_UPLOAD = this.SERVER_HOST + "resources/navpics/pictures/";

        this.SERVICE_ADVERT_PAGE = this.SERVER_HOST + "resources/adverts/";
        this.SERVICE_ADVERT_PAGE_QUERY = this.SERVICE_ADVERT_PAGE + "collections/";

        this.SERVICE_JOB_PAGE = this.SERVER_HOST + "resources/jobs/";
        this.SERVICE_JOB_PAGE_QUERY = this.SERVICE_JOB_PAGE + "collections/";

        this.SERVICE_POSTER_PAGE = this.SERVER_HOST + "resources/posters/";
        this.SERVICE_POSTER_PAGE_QUERY = this.SERVICE_POSTER_PAGE + "collections/";

        this.SERVICE_USER = this.SERVER_HOST + 'users/';
        this.SERVICE_USER_QUERY = this.SERVICE_USER + 'collections/';
        this.SERVICE_APPLICANT_QUERY = this.SERVICE_USER + 'applicants/collections/';
        this.SERVICE_CUSTOMER_QUERY = this.SERVICE_USER + 'customers/collections/';
        this.SERVICE_INTERVIEWING_COUNT = this.SERVICE_USER + 'interviewing/count/';

        this.SERVICE_LEARNING = this.SERVICE_USER + 'learnings/';
        this.SERVICE_LEARNING_QUERY = this.SERVICE_LEARNING + 'collections/';

        this.SERVICE_CHARACTER = this.SERVER_HOST + 'characters/';
        this.SERVICE_CHARACTER_QUERY = this.SERVICE_CHARACTER + 'collections/';

        this.SERVICE_ADMIN = this.SERVER_HOST + 'admins/';
        this.SERVICE_ADMIN_QUERY = this.SERVICE_ADMIN + 'collections/';

        this.SERVICE_LESSON_GROUP = this.SERVER_HOST + 'courses/lesson_groups/';
        this.SERVICE_LESSON_GROUP_QUERY = this.SERVICE_LESSON_GROUP + 'collections/';

        this.SERVICE_LESSON = this.SERVER_HOST + 'courses/lessons/';
        this.SERVICE_LESSON_QUERY = this.SERVICE_LESSON + 'collections/';

        this.SERVICE_OPEN_LESSON_GROUP = this.SERVER_HOST + 'courses/open_lesson_groups/';
        this.SERVICE_OPEN_LESSON_GROUP_QUERY = this.SERVICE_OPEN_LESSON_GROUP + 'collections/';

        this.SERVICE_OPEN_LESSON = this.SERVER_HOST + 'courses/open_lessons/';
        this.SERVICE_OPEN_LESSON_QUERY = this.SERVICE_OPEN_LESSON + 'collections/';

        this.SERVICE_COURSE = this.SERVER_HOST + 'courses/';
        this.SERVICE_COURSE_QUERY = this.SERVICE_COURSE + 'collections/';

        this.SERVICE_COURSE_CONFIG = this.SERVICE_COURSE + 'configs/';

        this.SERVICE_UEDITOR_UPLOAD = this.SERVER_HOST + "resources/ueditors/images/";

        this.SERVICE_COURSE_MEDIA_UPLOAD = this.SERVER_HOST + "courses/medias/";

        this.SERVICE_TURTLE_DICT = this.SERVER_HOST + "turtle/dictionaries/";
        this.SERVICE_TURTLE_DICT_QUERY = this.SERVICE_TURTLE_DICT + 'collections';

        this.SERVICE_TURTLE_WIKI_GROUP = this.SERVER_HOST + "turtle/wiki_groups/";
        this.SERVICE_TURTLE_WIKI_GROUP_QUERY = this.SERVICE_TURTLE_WIKI_GROUP + "collections";
        this.SERVICE_TURTLE_WIKI_GROUP_PIC_UPLOAD = this.SERVER_HOST + "turtle/wiki_groups/pictures/";

        this.SERVICE_TURTLE_QUESTION = this.SERVER_HOST + "turtle/questions/";
        this.SERVICE_TURTLE_QUESTION_QUERY = this.SERVICE_TURTLE_QUESTION + "collections";

        this.CKEDITOR_OPTIONS = {
            language: 'zh-CN',
            entities: false,
            // filebrowserImageUploadUrl: this.SERVER_HOST + 'resources/ckeditors/images?type=Images',
            readOnly: true
        };

        this.CKEDITOR_RES_IMAGE_PATH = this.SERVER_HOST + 'resources/ckeditors/images?type=Images&path=';

        this.UMEDITOR_CONFIG = {
            //这里可以选择自己需要的工具按钮名称,此处仅选择如下七个
            toolbar: ['source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
                'insertorderedlist insertunorderedlist | selectall cleardoc paragraph fontsize',
                '| justifyleft justifycenter justifyright justifyjustify |',
                'link unlink | emotion image |',
                'horizontal preview', 'formula'],
            //focus时自动清空初始化时的内容
            autoClearinitialContent: true,
            //关闭字数统计
            wordCount: false,
            //关闭elementPath
            elementPathEnabled: false,
            initialFrameWidth: '100%', //初始化编辑器宽度,默认500
            // initialFrameHeight: 500,  //初始化编辑器高度,默认500
            //zIndex : 5000,
            //frame高度
            //initialFrameHeight: 300
            imageUrl: this.SERVICE_UEDITOR_UPLOAD,
            imagePath: "",
            imageFieldName: "upfile",                   //图片数据的key,若此处修改，需要在后台对应文件修改对应参数
            'paragraph': {'p': '', 'h1': '', 'h2': '', 'h3': '', 'h4': '', 'h5': ''},
            'fontfamily': [
                {name: 'yahei', val: 'Microsoft Yahei'}
            ]
        };

    })
    .service('ErrorParserService', function () {
        this.parseHttpResponse = function (response) {
            var error_result = "<br>错误码：" + response.status + "  " + response.statusText;
            if (response.data && response.data.error) {
                error_result += "<br>错误信息：" + response.data.error;
            }
            return error_result;
        };
    })
    //会话服务，通过该服务，实现模块间的数据共享。并通过cookie技术，实现页面重新打开的时候的会话保持。
    .service('TokenService', function ($window, $rootScope) {
        //角色配置
        this.ROLES = {ROLE_USER: 1, ROLE_PAGE: 2, ROLE_COURSE: 4};

        //检测角色权限
        this.checkRole = function (role) {
            if (this.isAdmin()) {
                return true;
            }
            return (this.user.roleId & role) == role;
        };

        this.isAdmin = function () {
            return this.user.roleId == 100;
        };

        //登录
        this.login = function (response_data) {
            this.user.loginFlag = true;
            this.user.userId = response_data.userId;
            this.user.userName = response_data.userName;
            this.user.timestamp = new Date().getTime();
            this.user.expirePeriod = response_data.expirePeriod;
            this.user.token = response_data.token;
            this.user.refreshToken = response_data.refreshToken;
            this.user.roleId = response_data.roleId;
            $window.localStorage.setItem("manager_token", JSON.stringify(this.user));
            console.info("TokenService: login: post LoginStatusChanged login event...");
            $rootScope.$emit("LoginStatusChanged", "login");
        };
        //登出
        this.logout = function () {
            this.user = {
                loginFlag: false,
                userId: 0,
                userName: "",
                timestamp: new Date().getTime(),
                expirePeriod: 0,
                token: "",
                refreshToken: "",
                roleId: 0
            };
            $window.localStorage.removeItem("manager_token");
            console.info("TokenService: logout: post LoginStatusChanged logout event...");
            $rootScope.$emit("LoginStatusChanged", "logout");
        };
        //登录判断
        this.checkLogin = function () {
            // console.info("TokenService: checkLogin..");
            this.refresh();
            return this.user && this.user.loginFlag;
        };

        //是否登录
        this.isLogin = function () {
            return this.user && this.user.loginFlag;
        };

        //刷新Token
        this.refresh = function () {
            var last_login = this.isLogin();
            //加载缓存
            var token_data = $window.localStorage.getItem("manager_token");
            //为空，表示注销状态
            if (token_data == null) {
                this.user = {
                    loginFlag: false,
                    userId: 0,
                    userName: "",
                    timestamp: new Date().getTime(),
                    expirePeriod: 0,
                    token: "",
                    refreshToken: "",
                    roleId: 0
                };
                //如果之前是登录上的，则注销通知
                if (last_login == true) {
                    $rootScope.$emit("LoginStatusChanged", "logout");
                }
            }
            else {
                //解析，如果失败，则注销
                try {
                    this.user = JSON.parse($window.localStorage.getItem("manager_token"));
                    this.checkTokenRefresh();
                }
                catch (e) {
                    console.info("TokenService: refresh throws ex...");
                    this.user = {
                        loginFlag: false,
                        userId: 0,
                        userName: "",
                        timestamp: new Date().getTime(),
                        expirePeriod: 0,
                        token: "",
                        refreshToken: "",
                        roleId: 0
                    };
                    $window.localStorage.removeItem("manager_token");
                    if (last_login == true) {
                        $rootScope.$emit("LoginStatusChanged", "logout");
                    }
                }
            }
        };

        this.checkTokenRefresh = function () {
            //做时间判断，来决定是否需要进行Token刷新。通常我们设置超时时间的一半就要进行刷新
            if (this.isLogin() == false) {
                return;
            }
            var last_timestamp = this.user.timestamp;
            var this_time = new Date().getTime();
            var expire = this.user.expirePeriod;
            if (this_time - last_timestamp >= expire) {
                console.info("TokenService: checkTokenRefresh: Token is expired, logout.");
                this.logout();
            }
        };

        this.refresh();

        this.getRememberName = function () {
            var name = $window.localStorage.getItem("remember_name");
            return name ? name : "";
        };

        this.setRememberName = function (name) {
            if (name) {
                $window.localStorage.setItem("remember_name", name);
            }
            else {
                $window.localStorage.removeItem("remember_name");
            }
        };

    })
    .factory('tokenInjector', ['TokenService', function (TokenService) {
        var tokenInjector =
        {
            request: function (config) {
                if (TokenService.isLogin()) {
                    config.headers['Authorization'] = TokenService.user.token;
                }
                return config;
            }
        };
        return tokenInjector;
    }])
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('tokenInjector');
    }])
    //验证服务
    .service('EncryptService', function () {

        var hexcase = 0;
        /*   hex   output   format.   0   -   lowercase;   1   -   uppercase                 */
        var b64pad = "";
        /*   base-64   pad   character.   "="   for   strict   RFC   compliance       */
        var chrsz = 8;
        /*   bits   per   input   character.   8   -   ASCII;   16   -   Unicode             */

        this.encryptPassword = function (s) {
            return binb2b64(core_sha1(str2binb(s), s.length * chrsz));
        };

        /*
         *   Calculate   the   SHA-1   of   an   array   of   big-endian   words,   and   a   bit   length
         */
        function core_sha1(x, len) {
            /*   append   padding   */
            x[len >> 5] |= 0x80 << (24 - len % 32);
            x[((len + 64 >> 9) << 4) + 15] = len;

            var w = Array(80);
            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;
            var e = -1009589776;

            for (var i = 0; i < x.length; i += 16) {
                var olda = a;
                var oldb = b;
                var oldc = c;
                var oldd = d;
                var olde = e;

                for (var j = 0; j < 80; j++) {
                    if (j < 16) w[j] = x[i + j];
                    else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                    var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                    e = d;
                    d = c;
                    c = rol(b, 30);
                    b = a;
                    a = t;
                }

                a = safe_add(a, olda);
                b = safe_add(b, oldb);
                c = safe_add(c, oldc);
                d = safe_add(d, oldd);
                e = safe_add(e, olde);
            }
            return Array(a, b, c, d, e);

        }

        /*
         *   Add   integers,   wrapping   at   2^32.   This   uses   16-bit   operations   internally
         *   to   work   around   bugs   in   some   JS   interpreters.
         */
        function safe_add(x, y) {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return (msw << 16) | (lsw & 0xFFFF);
        }

        /*
         *   Bitwise   rotate   a   32-bit   number   to   the   left.
         */
        function rol(num, cnt) {
            return (num << cnt) | (num >>> (32 - cnt));
        }

        /*
         *   Convert   an   8-bit   or   16-bit   string   to   an   array   of   big-endian   words
         *   In   8-bit   function,   characters   >255   have   their   hi-byte   silently   ignored.
         */
        function str2binb(str) {
            var bin = Array();
            var mask = (1 << chrsz) - 1;
            for (var i = 0; i < str.length * chrsz; i += chrsz)
                bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (24 - i % 32);
            return bin;
        }


        /*
         *   Perform   the   appropriate   triplet   combination   function   for   the   current
         *   iteration
         */
        function sha1_ft(t, b, c, d) {
            if (t < 20) return (b & c) | ((~b) & d);
            if (t < 40) return b ^ c ^ d;
            if (t < 60) return (b & c) | (b & d) | (c & d);
            return b ^ c ^ d;
        }

        /*
         *   Determine   the   appropriate   additive   constant   for   the   current   iteration
         */
        function sha1_kt(t) {
            return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
        }

        /*
         *   Convert   an   array   of   big-endian   words   to   a   base-64   string
         */
        function binb2b64(binarray) {
            var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var str = "";
            for (var i = 0; i < binarray.length * 4; i += 3) {
                var triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);
                for (var j = 0; j < 4; j++) {
                    if (i * 8 + j * 6 > binarray.length * 32) str += b64pad;
                    else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
                }
            }
            // edit by zmmgiser
            var rest = binarray.length % 3;
            if (rest == 1)
                str += "==";
            if (rest == 2)
                str += "=";
            return str;
        }
    });